package com.example.extra.service.lmpl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.extra.common.CustomUserDetails;
import com.example.extra.entity.SysRolePermission;
import com.example.extra.entity.SysUser;
import com.example.extra.entity.SysUserCategory;
import com.example.extra.entity.SysUserRole;
import com.example.extra.mapper.SysRolePermissionMapper;
import com.example.extra.mapper.SysUserCategoryMapper;
import com.example.extra.mapper.SysUserMapper;
import com.example.extra.mapper.SysUserRoleMapper;

import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final SysUserMapper sysUserMapper;

    private final SysUserRoleMapper sysUserRoleMapper;

    private final SysRolePermissionMapper sysRolePermissionMapper;

    private final SysUserCategoryMapper sysUserCategoryMapper;

    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username", username));

        // 检查用户状态
        if (Objects.nonNull(user)) {
            if (user.getStatus() != 1) {
                throw new UsernameNotFoundException("User is disabled");
            }
            Long userId = user.getId();
            List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectList(Wrappers.lambdaQuery(SysUserRole.class).eq(SysUserRole::getUserId, userId));
            List<String> roleIds = new ArrayList<>();
            List<String> permissions = new ArrayList<>();
            List<String> categories = new ArrayList<>();

            if (CollectionUtil.isNotEmpty(sysUserRoles)) {
                roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId).map(p -> String.valueOf(p)).toList();
                List<Long> roleIdsQuery = roleIds.stream().map(Long::valueOf).toList();
                List<SysRolePermission> sysRolePermissions = sysRolePermissionMapper.selectList(Wrappers.lambdaQuery(SysRolePermission.class).in(SysRolePermission::getPermissionId, roleIdsQuery));
                if (CollectionUtil.isNotEmpty(sysRolePermissions)) {
                    permissions = sysRolePermissions.stream().map(SysRolePermission::getPermissionId).map(p -> String.valueOf(p)).toList();
                }
            }

            List<SysUserCategory> sysUserCategories = sysUserCategoryMapper.selectList(Wrappers.lambdaQuery(SysUserCategory.class).eq(SysUserCategory::getUserId, user.getId()));
            List<Long> list = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(sysUserCategories)) {
                list = sysUserCategories.stream().map(SysUserCategory::getCategoryId).toList();
//                if (CollectionUtil.isNotEmpty(list)) {
//                    List<PubDictItem> pubDictItems = pubDictItemMapper.selectList(Wrappers.lambdaQuery(PubDictItem.class).select(PubDictItem::getDictVal).in(PubDictItem::getId,list));
//                    if (CollectionUtil.isNotEmpty(pubDictItems)) {
//                        //这边存的是字典的val
//                        categories = pubDictItems.stream().map(PubDictItem::getDictVal).toList();
//                    }
//                }
            }
            return CustomUserDetails.create(user, list, roleIds, permissions);


        }
        return null;


        // 构建用户详情
        // return User.builder().username(user.getUsername()).password(user.getPassword()).authorities(getAuthorities(user)).accountExpired(false).accountLocked(false).credentialsExpired(false).build();
    }
}
